package com.cloud.template.base.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;

/**
 * json处理
 */
public class JsonUtil { 
	
	/**
	 * 把对象转换成json字符串
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj){
		String ret = "";
		ObjectMapper mapper = new ObjectMapper();
		try{
			ret = mapper.writeValueAsString(obj);
		}catch(Exception e){
			Logger.getLogger(JsonUtil.class).error(e.getMessage());
		}
		return ret;
	}
	/**
	 * 把json转换成对应的对象
	 * @param json
	 * @param entityClass
	 * @return
	 */
	public static <T> T fromJson(String json, Class<T> entityClass){
		T ret = null;
		try{
			ret = (new ObjectMapper()).readValue(json, entityClass);
		}catch(Exception e){
			ret = null;
		}
		return ret;
	}

}
